<?php
/**
 * Created by PhpStorm.
 * User: wo
 * Date: 2019/11/26
 * Time: 19:36
 */

namespace Home\Model;


use Think\Model;

class WishModel extends Model
{
    public function createOrder($id){

        $orderModel     = M('order');
        $memberModel    = M('member');
        $wishPayLog     = D('wish_pay_log');
        $orderExtm      = M('order_extm');
        $goods          = M('goods');
        $store          = M('store');
        $orderGoods     = M('order_goods');
        $goodsspec      = M('goods_spec');

        $info = $this->where(array('id'=>$id))->find();
        $conditions = 'w.spec_id = '.$info['spec_id'];
        $conditions .= ' AND w.id = '.$id;

        //查询匹配的规格信息
        $goodsSpecInfo = $this->alias('w')
            ->join("ecm_goods_spec s on s.spec_id = w.spec_id")
            ->where($conditions)
            ->field('s.*')
            ->find();

        if($info['num'] > $goodsSpecInfo['stock']){
            //1.退款
                $wishInfo = $wishPayLog->where(array('wish_id'=>$id))->select();
                foreach($wishInfo as $k=>$value){
                    $info['order_sn'] = $value['trade_no'];
                    $newArr['total_fee'] = $value['money'];
                    $newArr['refund_sn'] = $value['order_sn'];
                    if($value['pay_type'] == 1){
                        $info['payment_code'] = 'wxpay_app';
                    }else{
                        $info['payment_code'] = 'alipay_app';
                    }
                    $resultWishReturn = $this->refundSign($id);
                }
            //2.优惠券
             $res_cs = M('coupon_setting')->where(array('setting_id'=>3))->find();
            $data_coupon = array(
                'coupon_name' => $res_cs['name'],
                'money' => $res_cs['money'],
                'user_id' => $info['user_id'],
                'start_time' => time(),
                'end_time' => time() + $res_cs['coupon_setting'],
                'is_used' => 0,
                'remark' => $res_cs['remark']
            );
            M('member_coupon')->add($data_coupon);
            //3.改状态
            $data['finish_time'] = time();
            $data['state'] = 4;
            $res = $this->where(array('id'=>$id))->save($data);
            return;
        }

        $data['finish_time'] = time();
        $data['state'] = 2;
        $res = $this->where(array('id'=>$id))->save($data);
        if($res){

            //当前心愿单用户信息
            $memberInfo = $memberModel->where(array('user_id'=>$info['user_id']))->find();

            //当前心愿单支付信息
            $wishPayLogInfo = $wishPayLog->where(array('wish_id'=>$id))->find();
            //确定支付方式  1微信 2支付宝
            if($wishPayLogInfo['pay_type'] == 1){
                $payment_id = 1;
                $payment_name = '手机微信支付';
                $payment_code = 'wxpay_app';
            }elseif($wishPayLogInfo['pay_type'] == 2){
                $payment_id = 2;
                $payment_name = '手机支付宝支付';
                $payment_code = 'alipay_app';
            }
            if($goodsSpecInfo['stock'] < 1){
                return array('code'=>-1,'msg'=>'库存不足');
            }

//            减去规格中的库存
            $stock = $goodsSpecInfo['stock'] - $info['num'];
            $saveave['stock'] = $stock;
            $goodsspecSaveStock = $goodsspec->where(array('spec_id'=>$info['spec_id']))->save($saveave);
            if(!$goodsspecSaveStock){
                return array('code'=>-1,'msg'=>'库存修改失败');
            }

            //查询商品详细信息
            $goodsInfo = $goods->where(array('goods_id'=>$info['goods_id']))->find();
            //查询商家信息
            $storeInfo = $store->where(array('store_id'=>$goodsInfo['store_id']))->find();
            $pay1 = $wishPayLog->getPayLog($id,1);
            $pay2 = $wishPayLog->getPayLog($id,2);
            $goodsPrice = $pay1['smoney'] + $pay2['smoney'];
            //组合订单信息
            $arr = array(
                'order_sn'          => $this->_gen_order_sn(),
                'type'              => 'wishOrder',
                'extension'         => 'wish_normal',
                'seller_id'         => $goodsInfo['store_id'],
                'seller_name'       => $storeInfo['store_name'],
                'buyer_id'          => $info['user_id'],
                'buyer_name'          => $memberInfo['user_name'],
                'buyer_no'          => $memberInfo['user_no'],
                'phone_mob'          => $memberInfo['phone_mob'],
                'buyer_email'          => $memberInfo['email'],
                'add_time'          => time(),
                'status'            => 20,      //已支付状态
                'payment_id'        => $payment_id,      //支付方式id
                'payment_name'      => $payment_name,      //支付名称
                'payment_code'      => $payment_code,      //支付编码
                'out_trade_sn'      => $wishPayLogInfo['trade_no'],      //支付订单号
                'pay_time'          => $wishPayLogInfo['create_time'],      //支付时间
                'goods_amount'      => $info['goods_price'],      //合计金额
                'order_amount'      => $goodsPrice,      //实际付款金额
                'device'      => $info['device'],      //设备
            );
            $addOrderInfo = $orderModel->add($arr);
            if (!$addOrderInfo) {
                return array('code'=>-1,'msg'=>'生成订单失败');
            }
            //验证收货人地址信息
            $resAddress = $this->_valid_consignee_info($info['addr_id']);
            /* 插入收货人信息 */
            $resAddress['order_id'] = $addOrderInfo;
            $resOrderExtm = $orderExtm->add($resAddress);

            $goods_items = array(
                'order_id' => $addOrderInfo,
                'goods_id' => $goodsInfo['goods_id'],
                'goods_name' => $goodsInfo['goods_name'],
                'spec_id' => $info['spec_id'],
                'specification' => $goodsInfo['spec_name_1'].':'.$goodsSpecInfo['spec_1value'].' '.$goodsInfo['spec_name_2'].':'. $goodsSpecInfo['spec_2'],
                'price' => $goodsPrice,
                'quantity' => $info['num'],
                'goods_image' => $goodsSpecInfo['spec_1'],
                'goods_old_price' => $info['goods_price'],
                'price_amount' => $goodsPrice,
                'tax_price_amount' => round($goodsInfo['tax_price'] * $info['num'],2),
                'price_total' => $goodsPrice,
                'goods_type' => $goodsInfo['goods_type'] ? $goodsInfo['goods_type'] : 1,
                'promotions_id' => $goodsInfo['promotions_id'] ? $goodsInfo['promotions_id'] : 0,
            );
            $addOrderGoods = $orderGoods->add($goods_items);

            $this->where(array('id'=>$id))->save(array('order_id'=>$addOrderInfo));


            if($addOrderGoods){
                //推送oms订单
                $this->omsIndex($addOrderInfo);
                return array('code'=>1,'msg'=>'success');
            }
            return array('code'=>-1,'msg'=>'生成订单信息错误');
        }
        return array('code'=>-1,'msg'=>'网络错误');
    }


    function omsIndex($res_order)
    {
        /* 获取订单明细信息 */
        $model_order = M('order');
        $model_member = M('member');
        $coupon_mod = M('coupon');
        $goods_mod = M('goods');
        $member_mod = M('member');
        $goods_spec_mod = M('goods_spec');
        $storestock_mod = M('storestock');
        $tax_mod = M('my_tax');
        $unit_mod = M('unit');
        $order_goods_mod =  M('order_goods');
        $order_extm_mod = M('order_extm');
        $country_mod = M('country_info');
        $wrap_mod = M('wrap');
        $order_id = $res_order;
        $model_wish = M('wish');
        $order_info = $model_order->where(array('order_id'=>$order_id))->find();
        $order_goods = $order_goods_mod->where(array('order_id'=>$order_id))->select();
        $order_extm = $order_extm_mod->where(array('order_id'=>$order_id))->find();
        $member = $member_mod->where(array('user_id'=>$order_info['buyer_id']))->find();
        $wish = $model_wish->where(array('order_id'=>$order_id))->find();
        $send_data = $order_info;
        $send_data['order_goods'] = $order_goods;
        $send_data['order_extm'] = $order_extm;
        $send_data['member'] = $member;
        $send_data['wish'] = $wish;

        foreach ($send_data['order_goods'] as $k=>$v){
            $temp_goods_spec = $goods_spec_mod->where(array('spec_id'=>$send_data['order_goods'][$k]['spec_id']))->find();
            $temp_goods = $goods_mod->where(array('goods_id'=>$send_data['order_goods'][$k]['goods_id']))->find();
            $temp_storestock = $storestock_mod->where(array('storestock_id'=>$temp_goods_spec['spec_3value']))->find();
            $temp_tax = $tax_mod->where(array('tax_id'=>$temp_goods['tax_id']))->find();
            $temp_unit = $unit_mod->where(array('id'=>$temp_goods['unit_id']))->find();
            $temp_country = $country_mod->where(array('id'=>$temp_goods['country_id']))->find();
            $temp_wrap= $wrap_mod->where(array('id'=>$temp_goods['wrap_id']))->find();
            $send_data['order_goods'][$k]['spec'] = $temp_goods_spec;
            $send_data['order_goods'][$k]['goods'] = $temp_goods;
            $send_data['order_goods'][$k]['storestock'] = $temp_storestock;
            $send_data['order_goods'][$k]['tax'] = $temp_tax;
            $send_data['order_goods'][$k]['unit'] = $temp_unit;
            $send_data['order_goods'][$k]['country'] = $temp_country;
            $send_data['order_goods'][$k]['wrap'] = $temp_wrap;
        }

        $sen_data = $this->_get_oms_data($send_data);
        $res_wish = M('wish')->where( array('order_id'=>$order_id))->find();
        $res_pay = M('wish_pay_log')->where( array('wish_id'=>$res_wish['id']))->select();
//        $temp_pay = $this->_get_pay_data($order_info['order_sn'],$res_pay);
//        $sen_data['OrderPayments'] = $temp_pay;
        $url = C('OMS_WISH_URL'); #url 地址必须 http://xxxxx
        $asdasd = $this->_post_to_oms($url,$sen_data);
    }


    function _get_oms_data($data = array()){
        $return_array['OrderItets'] = array();
        $data['order_goods'] = (array)$data['order_goods'];
        foreach ($data['order_goods'] as $k => $v) {
            if(!array_key_exists($data['order_goods'][$k]['goods']['goods_id'],$return_array['OrderItets'])){
                $return_array['OrderItets'][$v['goods_id']]['ProductId'] = $data['order_goods'][$k]['goods']['goods_id'];
                $return_array['OrderItets'][$v['goods_id']]['ItemName'] = '爱莎';
                $return_array['OrderItets'][$v['goods_id']]['Unit'] = $data['order_goods'][$k]['unit']['unit_code'];
                $return_array['OrderItets'][$v['goods_id']]['Currency'] = '142';
                $return_array['OrderItets'][$v['goods_id']]['CiqCurrency'] = '156';
                $return_array['OrderItets'][$v['goods_id']]['Country'] = $data['order_goods'][$k]['country']['country_code'];
                $return_array['OrderItets'][$v['goods_id']]['CiqCountry'] = $data['order_goods'][$k]['country']['ciq_code'];
                $return_array['OrderItets'][$v['goods_id']]['WrapTypeCode'] = $data['order_goods'][$k]['wrap']['wrap_code'];
                //                test
                $return_array['OrderItets'][$v['goods_id']]['PurposeCode'] = '9';
                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = $data['seller_id'];
                $return_array['OrderItets'][$v['goods_id']]['StoreId'] = $data['seller_id'];
//                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = 16;

                $return_array['OrderItets'][$v['goods_id']]['ShelfGoodsName'] = $data['order_goods'][$k]['goods']['brand'];

                $return_array['OrderItets'][$v['goods_id']]['ProductSku'] = 'none';
                $return_array['OrderItets'][$v['goods_id']]['BarCode'] = 'none';


            }
            $return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'][] = array(
                'AttributeSku' => $data['order_goods'][$k]['spec']['sku'],
                'Quantity' => $data['order_goods'][$k]['quantity'],
                'Price' => $data['order_goods'][$k]['spec']['price'],
                'TaxRates' => $data['order_goods'][$k]['tax']['consolidated_tax'],
                'OrderTax' => $data['order_goods'][$k]['tax_price'],
                'OrderDiscount' => 0,
                'BarCode' => $data['order_goods'][$k]['spec']['barcode'],
                'TradeType' => $data['order_goods'][$k]['storestock']['stock_style'],
                'PriceInclTax' => $data['order_goods'][$k]['goods']['price'],
                'TotalPrice' => $data['order_goods'][$k]['price_total'],
                'WarehouseId' =>  $data['order_goods'][$k]['storestock']['stock_id'],
            );

        }
        $address_str = $this->emptyreplace($data['order_extm']['region_name']);
        $address_str = $address_str . $data['order_extm']['address'];
        $return_array['OtherNo'] = date("YmdHis",$data['wish']['add_time']).$data['wish']['id'];
        $return_array['LockInInventory'] = 20;
        $return_array['OrderStatusId'] = 10;
        $return_array['ShippingStatusId'] = 20;
        $return_array['PaymentStatusId'] = 30;
        $return_array['PaymentMethodSystemName'] = 'none';
        $return_array['ShippingMethod'] = 'ground';
        $return_array['CustomerCurrencyCode'] = '142';
        $return_array['AuthorizationTransactionResult'] = 'none';
        $return_array['OrderTotal'] = $data['goods_amount'];
        $return_array['AffiliateId'] = 0;
        $return_array['RefundedAmount'] = 0;
        $return_array['CreatedOnUtc'] = date("Y-m-d H:i:s");
        $return_array['OrderNo'] = $data['order_sn'];
        $return_array['BuyerName'] = $data['member']['real_name'] ? $data['member']['real_name'] : 'none';
        $return_array['BuyerTelephone'] = $data['phone_mob'];
        $return_array['BuyerRegNo'] = $data['phone_mob'];
        $return_array['BuyerIdType'] = 1;
        $return_array['BuyerIdNumber'] = $data['member']['user_no'] ? $data['member']['user_no'] : 'none';
        $return_array['PayCode'] = 'none';
        $return_array['PayName'] = 'none';
        $return_array['PayTransactionId'] = 'none';
        $return_array['Consignee'] = $data['order_extm']['consignee'];
        $return_array['ConsigneeTelephone'] = $data['order_extm']['phone_mob'];
        $return_array['ConsigneeAddress'] = $address_str;
        $return_array['IdCard'] = $data['order_extm']['user_no'] ? $data['order_extm']['user_no'] : 'none';
        $return_array['IdType'] = 1;
        $return_array['EtradeCountryCode'] = '156';
        $return_array['OrderPayments'] = array();
        $return_array['OrderItems'] = array();
        $return_array['OrderItems'] = array_values($return_array['OrderItets']);
        unset($return_array['OrderItets']);
        return $return_array;

    }

    function _get_pay_data($order_sn,$data){
        $return_array = array();
        foreach ($data as $k => $v){
            $return_array[] = array(
                'PayName' => $v['pay_type'] == 1 ? '财付通支付科技有限公司' : '支付宝(中国)网络技术有限公司',
                'OrderNo' => $order_sn,
                'WishNo' => $v['order_sn'],
                'PayTransactionId' => $v['trade_no'],
                'PayPrice' => $v['money'],
                'PayTime' => date("Y-m-d H:i:s",$v['create_time'])
            );
        }
        return $return_array;
    }

    function _post_to_oms($url,$data)
    {
        $data_string = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        $res = curl_exec($ch);
        if (!$res) {
            return false;
        } else {
            return json_decode($res,true);
        }
    }

    function emptyreplace($str)
    {
        $str = preg_replace('/\s+/',',',$str);
        return $str;
    }



    /**
     *    生成订单号
     *
     *    @author    Garbin
     *    @return    string
     */
    function _gen_order_sn() {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        $timestamp = time();
        $y = date('y', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        $orders = M('order')->where(array('order_sn'=>$order_sn))->find();
        if (empty($orders['order_sn'])) {
            /* 否则就使用这个订单号 */
            return $order_sn;
        }

        /* 如果有重复的，则重新生成 */
        return $this->_gen_order_sn();
    }

    /**
     *    验证收货人信息是否合法
     *
     *    @author    Garbin
     *    @param     array $consignee
     *    @return    void
     */
    function _valid_consignee_info($addr_id) {
        if (!$addr_id) {
            return;
        }
        //通过address_id  获取收货信息,存储到订单拓展表
        $address = M('address')->where(array('addr_id'=>$addr_id))->find();
        if(empty($address)){
            return;
        }
        $consignee['consignee'] = $address['consignee'];
        $consignee['region_id'] = $address['region_id'];
        $consignee['region_name'] = $address['region_name'];
        $consignee['user_no'] = $address['user_no'];
        $consignee['address'] = $address['address'];
        $consignee['zipcode'] = $address['zipcode'];
        $consignee['phone_mob'] = $address['phone_mob'];
        $consignee['shipping_fee'] = 0;
        $consignee['shipping_id'] = 0;
        $consignee['shipping_name'] = '商家包邮';
        return $consignee;
    }

    function refundSign($wish_id){
        if(!$wish_id){
            render('10400', '请选择心愿单');
        }
        $cond['wish_id'] = $wish_id;
        $cond['state'] = 1;
        $res_pay = M('wish_pay_log')->where($cond)->find();
        if(!$res_pay){
            render('10004', '未找到心愿单');
        }
        if($res_pay['pay_type'] == 1){
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Data.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Api.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Config.php";
            $input = new \WxPayRefund();
            $input->SetOut_trade_no($res_pay['order_sn']);
            $input->SetTotal_fee($res_pay['money'] * 100);
            $input->SetRefund_fee($res_pay['money'] * 100);
            $config = new \WxPay1Config();
            $input->SetOut_refund_no(date('YmdHis', time() + 8 * 3600) . rand(1000, 9999));
//            $input->SetOp_user_id($config->GetMerchantId());
            $rs = \WxPay1Api::refund($config,$input, 60);
//                $this->printf_info(WxPay1Api::refund($config,$input, 60));
            if($rs['return_code'] != 'SUCCESS'){
                render('10004', '退款失败');
            }
        }else if($res_pay['pay_type'] == 2){
            $config = include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/config.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
            include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
            //商户订单号，商户网站订单系统中唯一订单号
            $out_trade_no = trim($res_pay['order_sn']);

            //支付宝交易号
//                $trade_no = trim($_POST['WIDTRtrade_no']);
            //请二选一设置

            //需要退款的金额，该金额不能大于订单金额，必填
            $refund_amount = trim($res_pay['money']);

            //退款的原因说明
//                $refund_reason = trim($_POST['WIDTRrefund_reason']);

            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
//                $out_request_no = trim($_POST['WIDTRout_request_no']);

            //构造参数
            $RequestBuilder=new \AlipayTradeRefundContentBuilder();
            $RequestBuilder->setOutTradeNo($out_trade_no);
//                $RequestBuilder->setTradeNo($trade_no);
            $RequestBuilder->setRefundAmount($refund_amount);
//                $RequestBuilder->setOutRequestNo($out_request_no);
//                $RequestBuilder->setRefundReason($refund_reason);
            $aop = new \AlipayTradeService($config,true);
            $response = $aop->Refund($RequestBuilder);

            if($response->code != '10000'){
                render('10004', '退款失败');
            }
        }else{
            render('10004', '未找到心愿单');
        }

        $data_wish = array(
            'state' => 0,
            'finish_time' => time()
        );
        $res_pay = M('wish')->where(array('id'=>$wish_id))->save($data_wish);
        if($res_pay === false){
            render('10004', '修改状态失败');
        }
    }
}